package com.hhkj.admin.conf.service.base.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.hhkj.admin.conf.common.cont.ConfConst;
import com.hhkj.admin.conf.domain.Conf;
import com.hhkj.admin.conf.model.extend.Rule;
import com.hhkj.admin.conf.model.dopo.ConfDo;
import com.hhkj.admin.conf.model.dopo.ConfPo;
import com.hhkj.admin.conf.service.base.ConfService;
import com.hhkj.admin.conf.mapper.ConfMapper;
import com.ruoyi.common.base.biz.service.base.BaseServiceImpl;
import com.ruoyi.common.exception.GlobalException;
import com.ruoyi.common.utils.StringUtils;
import org.springframework.stereotype.Service;

/**
* @author admin
* @description 针对表【s_conf(系统配置表)】的数据库操作Service实现
* @createDate 2023-10-25 11:23:18
*/
@Service
public class ConfServiceImpl extends BaseServiceImpl<Conf, ConfDo, ConfPo, ConfMapper>
    implements ConfService{

    @Override
    public boolean updateEffectiveCodeBatch(Conf conf, ConfConst.EffectiveCode effectiveCode) {
        if (ObjectUtil.isEmpty(conf) || ObjectUtil.isEmpty(effectiveCode)) {
            return false;
        }
        LambdaUpdateWrapper<Conf> updateWrapper = new LambdaUpdateWrapper<Conf>()
                .eq(StringUtils.isNotBlank(conf.getCode()), Conf::getCode, conf.getCode())
                .eq(StringUtils.isNotBlank(conf.getEffectiveCode()), Conf::getEffectiveCode, conf.getEffectiveCode())
                .set(Conf::getEffectiveCode, effectiveCode.getCode());
        return update(updateWrapper);
    }

    public boolean updateRule(Rule ruleReq, ConfConst.Code code, Class<? extends Rule> entityClass) {
        ConfDo confDo = new ConfDo();
        confDo.setCode(code.getCode());
        confDo.setEffectiveCode(ConfConst.EffectiveCode.EFFECTIVE.getCode());
        this.updateEffectiveCodeBatch(confDo,ConfConst.EffectiveCode.INVALID);
        Rule rule = BeanUtil.toBean(ruleReq, entityClass);
        String conf = JSONUtil.toJsonStr(rule);
        confDo.setConf(conf);
        return this.save(confDo);
    }

    public <T> T getRule(ConfConst.Code code, Class<T> entityClass) {
        ConfDo confDo = new ConfDo();
        confDo.setCode(code.getCode());
        confDo.setEffectiveCode(ConfConst.EffectiveCode.EFFECTIVE.getCode());
        ConfPo confPo = this.getPoByDo(confDo);
        if (ObjectUtil.isEmpty(confPo)) {
            throw new GlobalException("规则不存在，请联系管理员");
        }
        String conf = confPo.getConf();
        T bean = JSONUtil.toBean(conf, entityClass);
        return bean;
    }

}




